package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import android.view.View;

import com.blockmeta.bbs.baselibrary.base.adapter.BaseAdapter;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.activity.base.BaseIMSearchActivity;
import com.blockmeta.bbs.immodule.activity.chat.UCGChatActivity;
import com.blockmeta.bbs.immodule.adapter.CircleForJoinAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.beaninterface.ICircleEntry;
import com.blockmeta.bbs.immodule.corebean.Impl.CircleDomainService;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.net.api.IMNetApi;
import com.blockmeta.bbs.immodule.net.pojo.SearchCirclesResponse;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

public class SearchCircleActivity extends BaseIMSearchActivity implements BaseQuickAdapter.OnItemClickListener , BaseQuickAdapter.RequestLoadMoreListener {


    private CircleForJoinAdapter mAdapter;
    private List<ICircleEntry> mICircleEntries=new ArrayList<>();

    private static final int PAGE_SIZE = 20;
    private int mPage = 1;
    private String mCircleName;
    @Override
    protected BaseAdapter getAdapter(){
        if (mAdapter==null){
            mAdapter = new CircleForJoinAdapter(R.layout.item_join_circle_list_hot,mICircleEntries);;

            //加入按钮点击
            mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId()!=R.id.btn_join){
                        return;
                    }
                    joinCircle(mICircleEntries.get(position).getId(), mICircleEntries.get(position).getCircleAuthRule()
                            ,mICircleEntries.get(position).getUserLevel(), position);
                }
            });
            //条目点击
            mAdapter.setOnItemClickListener(this);

            mAdapter.setOnLoadMoreListener(this,mRcvSearchList);
        }
        return mAdapter;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mEdtSearchInput.setHint("搜索圈子名称");
        setTitleText("搜索圈子");
    }

    @Override
    protected void searchOnNet(String content) {
        mPage = 1;
        mCircleName = content;
        mICircleEntries.clear();
        mAdapter.notifyDataSetChanged();
        searchCircles(content);
    }

    private void searchCircles(String content) {
        RetrofitFactory.getRetrofit().create(IMNetApi.SearchCircles.class)
                .searchCircles(content,mPage,PAGE_SIZE)
                .compose(this.<BaseCodeResponse<SearchCirclesResponse>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<SearchCirclesResponse>>rxSchedulerHelper())
                .compose(RxUtil.<SearchCirclesResponse>commonResultByCode())
                .subscribe(new IMSubscriber<SearchCirclesResponse>(mContext) {
                    @Override
                    public void onNext(SearchCirclesResponse o) {
                        if (o==null||o.list==null||o.list.size()==0){
                            mAdapter.loadMoreEnd(true);
                        }else {
                            mPage++;
                            mAdapter.loadMoreComplete();
                            mICircleEntries.addAll(o.list);
                            mAdapter.notifyDataSetChanged();
                        }
                        mAdapter.disableLoadMoreIfNotFullPage();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mAdapter.loadMoreFail();
                    }
                });
    }

    @Override
    protected View setEmptyView() {
        return getLayoutInflater().inflate(R.layout.empty_search_for_im,null);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        boolean joinState = mICircleEntries.get(position).getJoinState();
        long circleId = mICircleEntries.get(position).getId();
        //根据加入状态跳转不同界面。已加入的跳转聊天页面；未加入的跳转圈子详情页面。
        if (joinState){
            Intent intent = new Intent(mContext, UCGChatActivity.class);
            intent.putExtra(Params.USER_TAG,circleId);
            startActivity(intent);
        }else {
            Intent intent = new Intent(mContext, CircleDetailActivity.class);
            intent.putExtra(Params.CIRCLE_ID,circleId);
            intent.putExtra(Params.JOIN_STATE,false);
            startActivity(intent);
        }
    }

    /**
     * 加入推荐圈子
     * @param circleId 圈子ID
     * @param circleAuthRule
     * @param position
     */
    private void joinCircle(final long circleId, int circleAuthRule, int userLevel, final int position) {

        IMApplicationContext.getCircleDomainService().joinCircle(mContext, circleId, circleAuthRule, userLevel, new CircleDomainService.CircleJoinCallBack(){

            @Override
            public void onSuccess(String message) {

                //本地更新加入状态
                ICircleEntry item = mAdapter.getItem(position);
                if (item != null) {
                    item.setJoinState(true);
                }
                mAdapter.notifyItemChanged(position);
                RouterHelper.startActivity(mContext, RouterPath.IM_UCGChatActivity_ACTIVITY,String.valueOf(circleId));
            }

            @Override
            public void onFail() {

            }
        });
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        searchCircles(mCircleName);
    }
}
